package com.example.desksginktapp.viewmodels

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.baselibrary.bases.Constants
import com.example.httplibrary.https.ApiService
import com.example.httplibrary.https.NetworkUtils
import com.example.httplibrary.https.RetrofitClient
import com.xuexiang.xui.utils.XToastUtils
import com.zyf.baselibrary.base.BaseViewModel
import kotlinx.coroutines.launch

/**
 * @author 郑
 * @date 2025/8/4.
 * qq：331758871
 * phone：18979397268
 */
class MainViewModel : BaseViewModel() {

    private val _qrCode = MutableLiveData<String>()
    val qrCode: LiveData<String> = _qrCode
    fun getQrFromUrl() {
        val newUrl = mAcache?.getAsString(Constants.URL) ?: ""
        if (newUrl.isEmpty()) {
            XToastUtils.error("请先到右上角设置页面填写基础地址")
            return
        }
        RetrofitClient.setBaseUrl(newUrl)

        viewModelScope.launch {
            var apiServiceNo =
                RetrofitClient.createServiceWithoutCommonParams(ApiService::class.java)
            NetworkUtils.safeApiCallWithCallbacks(
                apiCall = { apiServiceNo.getTemporaryVisitorQrCode() },
                onSuccess = { data ->
                    // 更简洁的处理逻辑
                    when {
                        data?.code == 200 && !data.message.isNullOrEmpty() -> {
                            _qrCode.value = data.message
                        }
                        data?.code == 200 -> {
                            XToastUtils.error("获取二维码失败：返回数据为空")
                        }
                        else -> {
                            XToastUtils.error(data?.message ?: "获取二维码失败")
                        }
                    }
                },
                onError = { code, message ->
                    XToastUtils.error("获取二维码失败")
                })

        }
    }
}